<?php
declare (strict_types = 1);
namespace app\admin\model;
use app\admin\model\UserBalanceLog as UserBalanceLogModel;
use app\admin\model\UserPointsLog as UserPointsLogModel;
use app\admin\model\UserGradeLog as UserGradeLogModel;
/**
 * 用户模型
 */
class User extends BaseModel
{
	
	// 定义表名
    protected $name = 'User';

    // 定义主键
    protected $pk = 'user_id';

    // 追加字段
    // protected $append = [''];

    /**
     * [filter 查询条件过滤器]
     * Author：上官钧墨
     * @return $data [被过滤数组]
     */
    private function filter($data=[])
    {
 		// 设置要查询的字段
    	$default = [
    		$this->pk=>'',
    		'nick_name'=>'',
    		'search'=>'',
    		'grade_id'=>'',
    	];
    	// 合并数据，以设置为准
    	$params = $this->setDefaultValue($data,$default);
    	$filter = [];
        $filter[] = ['is_delete', '=' , 0];
    	// 更多查询条件......
    	!empty($params[$this->pk]) && $filter[] = [$this->pk, '=', $params[$this->pk]];
    	// 用户呢称/手机号
        !empty($params['search']) && $filter[] = ['nick_name|mobile', 'like', "%{$params['search']}%"];
        // 用户等级
        isset($params['grade_id']) && $params['grade_id'] > 0 && $filter[] = ['grade_id', '=', (int)$params['grade_id']];
        // 起止时间
        if (!empty($params['create_time'])) {
            $times = betweenTime($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }
     /**
     * [getList 获取菜单树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function getList($data)
    {
        $hidden = ['update_time','password'];
        $page = 1;//设置页码
		$listRows = 15;//设置每页条数

		isset($data['page']) && !empty((int)$data['page'])?$page = $data['page']:$page;
		isset($data['listRows']) && !empty((int)$data['listRows'])?$page = $data['listRows']:$page;
		$model = $this->where($this->filter($data));
		$total = $model->count();
        $list = $model->with(['grade'])->page($page,$listRows)->hidden($hidden)->select();
        return ['page'=>$page,'total'=>$total,'listRows'=>$listRows,'list'=>$list];
    }
    /**
     * [updateGrade 更新等级]
     * @return [type]        [description]
     */
    public function updateGrade($data,$detail)
    {
    	$model = new UserGradeLogModel;
    	$this->startTrans();
		$res = $this->where(['user_id'=>$data['user_id']])->update(['grade_id'=>$data['grade_id']]);
		if (!$res) {
			$this->error = '设置失败，请重试';
			$this->rollback();
			return false;
		}
		// 写入日志
		$log = [
			'user_id'=>$data['user_id'],
			'change_type'=>10,//10后台管理员设置 20自动升级
			'old_grade_id'=>$detail['grade_id'],
			'new_grade_id'=>$data['grade_id'],
			'remark'=>$data['remark'],
			'create_time'=>time(),
		];
		$resLog = $model->insert($log);
		if (!$resLog) {
			$this->error = '设置失败，请重试';
			$this->rollback();
			return false;
		}
		$this->commit();
		return true;
    }
    /**
     * [充值]
     */
    public function recharge($data)
    {
    	$user = $this->userInfo();
    	
    	$UserPointsLogModel = new UserPointsLogModel;
    	// 余额变更
		if ($data['activeKey'] == 'balance') {
			if ($data['balanceChangeType'] == 'inc') {
				# 增加
				$this->startTrans();
				$res = $this->setInc(['user_id'=>$data['user_id']],'balance',$data['amount']);
				if (!$res) {
					$this->error = '金额增加失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->balanceLog($data['user_id'],$data['balanceChangeType'],30,$data['amount'],$data['balanceRemark']);
				if (!$resLog) {
					$this->error = '金额增加失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
			if ($data['balanceChangeType'] == 'dec') {
				# 减少
				$this->startTrans();
				$res = $this->setDec(['user_id'=>$data['user_id']],'balance',$data['amount']);
				if (!$res) {
					$this->error = '金额减少失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->balanceLog($data['user_id'],$data['balanceChangeType'],30,$data['amount'],$data['balanceRemark']);
				if (!$resLog) {
					$this->error = '金额减少失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
			if ($data['balanceChangeType'] == 'final') {
				# 目标
				$this->startTrans();
				$res = $this->where(['user_id'=>$data['user_id']])->update(['balance'=>$data['amount']]);
				if (!$res) {
					$this->error = '金额设置失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->balanceLog($data['user_id'],$data['balanceChangeType'],30,$data['amount'],$data['balanceRemark']);
				if (!$resLog) {
					$this->error = '金额设置失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
		}
		// 积分变更
		if ($data['activeKey'] == 'points') {
			if ($data['pointsChangeType'] == 'inc') {
				# 增加
				$this->startTrans();
				$res = $this->setInc(['user_id'=>$data['user_id']],'points',$data['quantity']);
				if (!$res) {
					$this->error = '金额增加失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->pointsLog($data['user_id'],$data['pointsChangeType'],30,$data['quantity'],$data['pointsRemark']);
				if (!$resLog) {
					$this->error = '金额增加失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
			if ($data['pointsChangeType'] == 'dec') {
				# 减少
				$this->startTrans();
				$res = $this->setDec(['user_id'=>$data['user_id']],'points',$data['quantity']);
				if (!$res) {
					$this->error = '金额减少失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->pointsLog($data['user_id'],$data['pointsChangeType'],30,$data['quantity'],$data['pointsRemark']);
				if (!$resLog) {
					$this->error = '金额减少失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
			if ($data['pointsChangeType'] == 'final') {
				# 目标
				$this->startTrans();
				$res = $this->where(['user_id'=>$data['user_id']])->update(['points'=>$data['quantity']]);
				if (!$res) {
					$this->error = '金额设置失败，请重试';
					$this->rollback();
					return false;
				}
				$resLog = $this->pointsLog($data['user_id'],$data['pointsChangeType'],30,$data['quantity'],$data['pointsRemark']);
				if (!$resLog) {
					$this->error = '金额设置失败，请重试 -1';
					$this->rollback();
					return false;
				}
				$this->commit();
				return true;
			}
		}
    }
    /**
     * [余额变动记录]
     * @param  [type]  $user_id     [会员id]
     * @param  [type]  $change_type [变动类型]
     * @param  integer $scene       [变动场景]
     * @param  [type]  $money       [变动金额]
     * @param  [type]  $remark      [变动说明]
     */
    private function balanceLog($user_id,$change_type,$scene=30,$money,$remark)
    {
    	$model = new UserBalanceLogModel;
    	$text = '设置为';
    	$type = 40;
    	if ($change_type=='inc') {
    		$type = 10;
    		$text = '增加';
    	}
    	if ($change_type=='dec') {
    		$type = 20;
    		$text = '减少';
    	}
    	if ($change_type=='final') {
    		$type = 30;
    		$text = '设置为';
    	}

    	$user = $this->userInfo();
    	// 写入日志
		$log = [
			'user_id'=>$user_id,
			'change_type'=>$type,//10增加,20减少，30最终，40不变
			'scene'=>$scene,//10用户充值 20用户消费 30管理员操作 40订单退款
			'money'=>$money,
			'describe'=>'管理员：'.$user['user_name'].'['.$user['admin_user_id'].']给用户ID:'.$user_id.'的可用余额'.$text.'￥：'.$money,
			'remark'=>$remark,
			'create_time'=>time(),
		];
		$resLog = $model->insert($log);
		if (!$resLog) {
			return false;
		}
		return true;
    }
    /**
     * [积分变动记录]
     * @param  [type]  $user_id     [会员id]
     * @param  [type]  $change_type [变动类型]
     * @param  integer $scene       [变动场景]
     * @param  [type]  $money       [变动金额]
     * @param  [type]  $remark      [变动说明]
     */
    private function pointsLog($user_id,$change_type,$scene=20,$money,$remark)
    {
    	$model = new UserPointsLogModel;
    	$text = '设置为';
    	$type = 40;
    	if ($change_type=='inc') {
    		$type = 10;
    		$text = '增加';
    	}
    	if ($change_type=='dec') {
    		$type = 20;
    		$text = '减少';
    	}
    	if ($change_type=='final') {
    		$type = 30;
    		$text = '设置为';
    	}

    	$user = $this->userInfo();
    	// 写入日志
		$log = [
			'user_id'=>$user_id,
			'change_type'=>$type,//10增加,20减少，30最终，40不变
			'scene'=>$scene,//10用户消费 20管理员操作30订单退款
			'quantity'=>$money,
			'describe'=>'管理员：'.$user['user_name'].'['.$user['admin_user_id'].']给用户ID:'.$user_id.'的可用积分'.$text.'￥：'.$money,
			'remark'=>$remark,
			'create_time'=>time(),
		];
		$resLog = $model->insert($log);
		if (!$resLog) {
			return false;
		}
		return true;
    }
    /**
     * [获取等级]
     */
    public function grade()
    {
    	return $this->belongsTo("app\admin\model\UserGrade", 'grade_id');
    }
    /**
     * [detail 获取详情]
     * Author：上官钧墨
     * @param  [type] $where [条件]
     */
    public function detail($where=[], $with = [],$hidden = [])
    {
        is_array($where) ? $filter = $where : $filter[$this->pk] = (int)$where;
        return $this->get($filter, $with,$hidden);
    }
}